package com.ys.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ys.WebConstants;
import com.ys.extend.common.model.AjaxJson;
import com.ys.extend.utils.ContextHolderUtils;
import com.ys.web.entity.User;
import com.ys.web.pojo.AccountInfo;
import com.ys.web.pojo.BackupDescription;
import com.ys.web.pojo.BackupInfo;
import com.ys.web.pojo.CompanyHasBackup;
import com.ys.web.pojo.CompanyInfo;
import com.ys.web.pojo.CustomerFollowUp;
import com.ys.web.pojo.SystemPermissonInfo;
import com.ys.web.remotemodel.AdOfflineCompanyInfo;
import com.ys.web.remotemodel.RemoteAccountInfo;
import com.ys.web.security.SystemPermissionUtils;
import com.ys.web.service.AccountService;
import com.ys.web.service.BackupService;
import com.ys.web.service.CompanyService;
import com.ys.web.service.FollowUpService;
import com.ys.web.service.OptimizationStrategyService;
import com.ys.web.ws.service.OsCompanyInfoService;

/**
 * 代运营公司
 * 
 * @author wdj
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/companyController")
public class CompanyController extends HttpServlet {

	@Autowired
	private CompanyService companyService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private BackupService backupService;
	@Autowired
	private OptimizationStrategyService optimizationStrategy;
	@Autowired
	private FollowUpService followUpService;
	@Resource
	private OsCompanyInfoService osCompanyInfoService;

	/**
	 * 显示经理-SEM分配管理
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(params = "showManageCompany")
	public ModelAndView companyIndex(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/companyList");
	}

	/**
	 * 显示推广数据管理
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(params = "showSemCompany")
	public ModelAndView companySemIndex(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/companySemList");
	}

	/**
	 * 显示创意报告管理
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(params = "showOriginalityReport")
	public ModelAndView showOriginalityReport(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/originalityReport");
	}

	/**
	 * 推广数据备份
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(params = "manageBackupCompany")
	public ModelAndView companyBackupIndex(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/manageBackupCompany");
	}

	@RequestMapping(params = "semBackupCompany")
	public ModelAndView semCompanyBackupIndex(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/semBackupCompany");
	}

	@RequestMapping(params = "semShowGoodCompany")
	public ModelAndView semShowCompanyBackupIndex(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/semShowGoodCompany");
	}

	/**
	 * 优秀账户备份
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(params = "showGoodCompany")
	public ModelAndView showGoodCompanyIndex(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/showGoodCompany");
	}

	/**
	 * 客户跟进管理跳转页面
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(params = "customerFollowUp")
	public ModelAndView customerFollowUp(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/customerFollowUp");
	}

	@RequestMapping(params = "deleteBackup")
	@ResponseBody
	public String deleteCompanyBackup(HttpServletRequest httpServletRequest) {
		Integer id = Integer.valueOf(httpServletRequest.getParameter("id"));

		try {

			companyService.deleteCompanyBackup(id);

			return "success";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}

	}

	@RequestMapping(params = "deleteAllBackup")
	@ResponseBody
	public AjaxJson deleteCompanyAllBackup(HttpServletRequest httpServletRequest) {
		Integer compangId = Integer.valueOf(httpServletRequest.getParameter("id"));
		AjaxJson ajaxJson = new AjaxJson();

		try {

			companyService.deleteCompanyAllBackup(compangId);
			ajaxJson.setMsg("success");
			return ajaxJson;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(params = "signBackup")
	@ResponseBody
	public AjaxJson signCompanyBackup(HttpServletRequest httpServletRequest) {
		Integer id = Integer.valueOf(httpServletRequest.getParameter("id"));
		AjaxJson ajaxJson = new AjaxJson();

		try {
			companyService.signCompanyBackup(id);
			ajaxJson.setMsg("success");

			return ajaxJson;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(params = "downloadBackup")
	@ResponseBody
	public void downloadBackup(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

		Integer companyId = Integer.valueOf(httpServletRequest.getParameter("id"));

		List<String> paths = new ArrayList();

		try {

			paths = backupService.getBackupInfoById(companyId);

			String filename = paths.get(0);
			// 设置Content-Disposition
			httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + filename);
			httpServletResponse.setContentType("application/octet-stream ");
			File file = new File(paths.get(0));

			paths.set(0, file.getAbsolutePath());

			// 读取目标文件，通过response将目标文件写到客户端
			// 获取目标文件的绝对路径
			String fullFileName = paths.get(0);
			// System.out.println(fullFileName);
			// 读取文件
			InputStream in = new FileInputStream(fullFileName);
			OutputStream out = httpServletResponse.getOutputStream();
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}

			in.close();
			out.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}

	}

	// /**
	// * 显示-广告到期公司信息
	// * @param httpServletRequest
	// * @return
	// */
	// @RequestMapping(params="showAdOfflineCompany")
	// public ModelAndView showAdOfflineCompany(HttpServletRequest
	// httpServletRequest){
	// return new ModelAndView("company/adOfflineCompanyList");
	// }

	/**
	 * 显示普通SEM-公司-推广账号管理
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(params = "showSemCompanyDo")
	public ModelAndView showSemCompanyDo(HttpServletRequest httpServletRequest) {
		return new ModelAndView("company/companyListSemtDo");
	}

	@RequestMapping(params = "getCompanys")
	@ResponseBody
	public List<CompanyInfo> getCompanyPage(Integer page, HttpSession session) {
		String username = (String) session.getAttribute("username");

		Integer userId = (Integer) session.getAttribute("userId");
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		if (username != null && userId != null) {

			SystemPermissonInfo systemPermissonInfo = SystemPermissionUtils.getUserPermission(username);
			Integer infopage = 1;
			if (page != null) {
				infopage = page;
			}

			try {
				if (systemPermissonInfo.getRoleId().contains(WebConstants.SUPER_USER)
						|| systemPermissonInfo.getRoleId().contains(WebConstants.SEM_MANAGER_USER)) {
					// companyInfos=companyService.getCompanyBySemUserId(null,
					// infopage);
					companyInfos = companyService.getRemoteCompanyBySemUserId(null, infopage);
				} else {
					// companyInfos =
					// companyService.getCompanyBySemUserId(userId, infopage);
					companyInfos = companyService.getRemoteCompanyBySemUserId(userId, infopage);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return companyInfos;

	}

	/**
	 * 更新公司信息
	 * 
	 * @param companyInfo
	 * @return
	 */
	// 待完善
	@RequestMapping(params = "saveCompany")
	@ResponseBody
	public AjaxJson saveCompany(@RequestBody CompanyInfo companyInfo) {
		AjaxJson ajaxJson = new AjaxJson();
		String companyName = companyInfo.getCompanyName();
		if (companyName == null || companyName.equals("")) {
			ajaxJson.setMsg("公司名不能空");
			ajaxJson.setSuccess(false);
			return ajaxJson;
		}

		// Integer industryId = companyInfo.getIndustryId();
		String industryId = companyInfo.getIndustryId();

		if (industryId == null) {
			ajaxJson.setMsg("你没有选择行业");
			ajaxJson.setSuccess(false);
		}

		Integer semId = companyInfo.getUserId();
		if (semId == null) {
			ajaxJson.setMsg("你没有分配sem用户");
			ajaxJson.setSuccess(false);
		}
		try {
			if (companyInfo.getId() == null) {
				if (companyService.isCompanyNameExist(companyName)) {
					ajaxJson.setMsg("此公司已存在");
					ajaxJson.setSuccess(false);
					return ajaxJson;
				}
			}

			// 更新公司信息
			companyService.updateCompanyInfo(companyInfo);
			// Integer companyId= companyService.saveCompanyInfo(companyInfo);

			// //已添加重复账户名
			// if(companyId==-1){
			// ajaxJson.setMsg("添加重复了的账户名");
			// ajaxJson.setSuccess(false);
			// return ajaxJson;
			// }
			// List<RemoteAccountInfo>
			// accountInfos=accountService.getAccountByCompanyKADId(companyId);
			// String key = CacheKeyGenerator.generateQueryCacheKey(userId,
			// AccountInfo.class.getName(), List.class.getName(),
			// companyId.toString());
			// QueryCache.updateQueryObject(key, accountInfos);

			ajaxJson.setMsg("操作成功");
			ajaxJson.setSuccess(true);
			return ajaxJson;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ajaxJson.setMsg("操作异常");
			ajaxJson.setSuccess(false);
			return ajaxJson;
		}

	}

	@RequestMapping(params = "addCompany")
	@ResponseBody
	public AjaxJson addCompany(@RequestBody CompanyInfo companyInfo) {
		AjaxJson ajaxJson = new AjaxJson();

		try {
			companyService.addCompanyInfo(companyInfo);
			ajaxJson.setMsg("success");
			return ajaxJson;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(params = "delCompany")
	@ResponseBody
	public AjaxJson deleteCompany(Integer id) {
		AjaxJson ajaxJson = new AjaxJson();

		try {
			companyService.deleteCompany(id);
			ajaxJson.setMsg("success");
			return ajaxJson;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(params = "checkAccount")
	@ResponseBody
	public String checkBaiduAccount(Integer companyId) {
		if (companyId != null) {
			try {
				List<RemoteAccountInfo> accountInfos = accountService.getAccountByCompanyKADId(companyId);
				if (accountInfos != null && !accountInfos.isEmpty()) {
					for (AccountInfo accountInfo : accountInfos) {
						if ("baidu".equals(accountInfo.getTypeTag())) {
							return accountInfo.getId().toString();
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();

			}

		}
		return WebConstants.FAIL_CODE;

	}

	@RequestMapping(params = "checkCompanyName")
	@ResponseBody
	public String checkCompanyName(String companyName) {
		try {
			// System.out.println("companyName:"+companyService.isCompanyNameExist(companyName));
			// 不存在则返回成功
			if (!companyService.isCompanyNameExist(companyName)) {
				return WebConstants.SUCCESS_CODE;
			} else {
				return WebConstants.FAIL_CODE;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return WebConstants.FAIL_CODE;
		}
	}

	/**
	 * 获取广告到期的公司信息
	 * 
	 * @param companyName
	 * @return
	 */
	@RequestMapping(params = "getAdOfflineCompany")
	@ResponseBody
	@Deprecated
	public List<AdOfflineCompanyInfo> getAdOfflineCompany(Integer page, HttpSession session) {
		String username = (String) session.getAttribute("username");
		Integer userId = (Integer) session.getAttribute("userId");
		List<AdOfflineCompanyInfo> companyInfos = new ArrayList<AdOfflineCompanyInfo>();
		if (username != null && userId != null) {
			SystemPermissonInfo systemPermissonInfo = SystemPermissionUtils.getUserPermission(username);
			Integer infopage = 1;
			if (page != null) {
				infopage = page;
			}
			try {
				if (systemPermissonInfo.getRoleId().contains(WebConstants.SUPER_USER)
						|| systemPermissonInfo.getRoleId().contains(WebConstants.SEM_MANAGER_USER)) {
					companyInfos = companyService.getAdOfflineCompanyInfo_ws(null, infopage);
				} else {
					companyInfos = companyService.getAdOfflineCompanyInfo_ws(userId, infopage);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return companyInfos;
	}

	/**
	 * 获取百度推广的公司
	 * 
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping(params = "getbaiduCompanys")
	@ResponseBody
	public List<CompanyInfo> getbaiduCompanys(Integer page, HttpSession session) {
		String username = (String) session.getAttribute("username");

		Integer userId = (Integer) session.getAttribute("userId");
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		if (username != null && userId != null) {

			SystemPermissonInfo systemPermissonInfo = SystemPermissionUtils.getUserPermission(username);
			Integer infopage = 1;
			if (page != null) {
				infopage = page;
			}

			try {
				if (systemPermissonInfo.getRoleId().contains(WebConstants.SUPER_USER)
						|| systemPermissonInfo.getRoleId().contains(WebConstants.SEM_MANAGER_USER)) {
					companyInfos = companyService.getRemoteCompanyBySemUserId_baidu(null, infopage);
				} else {
					companyInfos = companyService.getRemoteCompanyBySemUserId_baidu(userId, infopage);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return companyInfos;

	}

	@RequestMapping(params = "getCompanysAndIsGood")
	@ResponseBody
	public List<CompanyHasBackup> getCompanysAndIsGood(Integer page, HttpSession session) {
		String username = (String) session.getAttribute("username");
		List<CompanyHasBackup> companyHasBackups = new ArrayList();
		Integer userId = (Integer) session.getAttribute("userId");
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		if (username != null && userId != null) {

			SystemPermissonInfo systemPermissonInfo = SystemPermissionUtils.getUserPermission(username);
			Integer infopage = 1;
			if (page != null) {
				infopage = page;
			}

			try {
				if (systemPermissonInfo.getRoleId().contains(WebConstants.SUPER_USER)
						|| systemPermissonInfo.getRoleId().contains(WebConstants.SEM_MANAGER_USER)) {
					companyInfos = companyService.getRemoteCompanyBySemUserId_baidu(null, infopage);
				} else {
					companyInfos = companyService.getRemoteCompanyBySemUserId_baidu(userId, infopage);
				}

				for (CompanyInfo companyInfo : companyInfos) {
					CompanyHasBackup companyHasBackup = new CompanyHasBackup();
					companyHasBackup.setId(companyInfo.getId());
					companyHasBackup.setCompanyName(companyInfo.getCompanyName());
					companyHasBackup.setIndustry(companyInfo.getIndustry());
					companyHasBackup.setUsername(companyInfo.getUsername());
					String isGood = backupService.getBackupIsGood(companyInfo.getId());
					companyHasBackup.setIsGood(isGood);
					Integer hasPath = backupService.getBackupHasPath(companyInfo.getId());
					companyHasBackup.setHasPath(hasPath);
					companyHasBackups.add(companyHasBackup);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return companyHasBackups;

	}

	@RequestMapping(params = "getBackupCompany")
	@ResponseBody
	public List<BackupInfo> getBackupCompanys(Integer page, HttpSession session) {
		List<BackupInfo> backupInfos = new ArrayList();
		backupInfos = backupService.getBackupInfo();
		for (BackupInfo b : backupInfos) {
			System.out.println(b.getCreateTime());
		}

		return backupInfos;
	}

	@RequestMapping(params = "cancelGoodBackup")
	@ResponseBody
	public AjaxJson cancelCompanyBackup(HttpServletRequest httpServletRequest) {
		Integer id = Integer.valueOf(httpServletRequest.getParameter("companyId"));
		AjaxJson ajaxJson = new AjaxJson();

		try {
			companyService.cancelCompanyBackup(id);
			ajaxJson.setMsg("success");
			return ajaxJson;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	// public List<BackupDescription> getBackupPaths(HttpServletRequest
	// httpServletRequest){
	// Integer companyId =
	// Integer.valueOf(httpServletRequest.getParameter("id"));
	// List<BackupDescription> backupPaths =
	// backupService.getBackupDescription(companyId);
	// return backupPaths;
	//
	// }

	@RequestMapping(params = "getBackupDescription")
	public ModelAndView getBackupDescription(HttpServletRequest httpServletRequest) {

		ModelAndView mav = new ModelAndView("company/manageBackupList");
		Integer id = Integer.valueOf(httpServletRequest.getParameter("id"));

		if (id != null && id != 0) {
			mav.addObject("companyId", id);
		} else {
			try {
				throw new Exception("companyId参数为null");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return mav;
	}

	@RequestMapping(params = "getBackupDescriptionList")
	@ResponseBody
	public List<BackupDescription> getBackupDescriptionList(HttpServletRequest httpServletRequest) {
		Integer companyId = Integer.valueOf(httpServletRequest.getParameter("companyId"));
		List<BackupDescription> backupDescription = backupService.getBackupDescription(companyId);
		return backupDescription;

	}

	@RequestMapping(params = "getSemBackupDescription")
	public ModelAndView getSemBackupDescription(HttpServletRequest httpServletRequest) {

		ModelAndView mav = new ModelAndView("company/semBackupList");
		Integer id = Integer.valueOf(httpServletRequest.getParameter("id"));

		if (id != null && id != 0) {
			mav.addObject("companyId", id);
		} else {
			try {
				throw new Exception("companyId参数为null");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return mav;
	}

	@RequestMapping(params = "optimizationStrategy")
	@ResponseBody
	public AjaxJson optimizationStrategy(HttpServletRequest httpServletRequest) {
		Integer companyId = Integer.valueOf(httpServletRequest.getParameter("companyId"));
		String industryId = String.valueOf(httpServletRequest.getParameter("industryId"));
		String industryName = httpServletRequest.getParameter("industryName");
		StringBuffer str = new StringBuffer();
		AjaxJson ajaxJson = new AjaxJson();
		if (optimizationStrategy.isExist(companyId)) {
			ajaxJson.setMsg(optimizationStrategy.getOptimizationTrategy(companyId));
			return ajaxJson;
		} else {
			str.append(optimizationStrategy.rationRule(companyId, industryId, industryName));
			str.append(optimizationStrategy.variableRule(companyId, industryId, industryName));
			String result = str.toString();
			StringBuffer sb = new StringBuffer();
			StringBuffer sb1 = new StringBuffer();
			String[] split = result.split("</br>");
			for (String s : split) {
				if (!"".equals(s)) {
					sb1.append(s).append("</br>");
				}
			}
			String[] re = sb1.toString().split("</br>");
			for (int i = 1; i <= re.length; i++) {
				sb.append(i).append(". ").append(re[i - 1]).append("\n").append("</br>");
			}
			optimizationStrategy.saveOptimizationTrategy(companyId, sb.toString());
			ajaxJson.setMsg(sb.toString());
			ajaxJson.setSuccess(true);
			return ajaxJson;
		}
	}

	@RequestMapping(params = "getcustomerFollowUp")
	@ResponseBody
	public List<CustomerFollowUp> getcustomerFollowUp(Integer page, Integer rows, HttpSession session) {
		String operateUsername = (String) session.getAttribute("username");
		Integer operateUserId = (Integer) session.getAttribute("userId");
		List<CustomerFollowUp> customerFollowUp = new ArrayList<CustomerFollowUp>();
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		if (operateUsername != null && operateUserId != null) {
			SystemPermissonInfo systemPermissonInfo = SystemPermissionUtils.getUserPermission(operateUsername);
			if (systemPermissonInfo.getRoleId().contains(WebConstants.SUPER_USER)
					|| systemPermissonInfo.getRoleId().contains(WebConstants.SEM_MANAGER_USER)) {
				companyInfos = companyService.getRemoteCompanyBySemUserId_baidu(null, 1);
			} else {
				companyInfos = companyService.getRemoteCompanyBySemUserId_baidu(operateUserId, 1);
			}
			if (companyInfos != null && !companyInfos.isEmpty()) {
				for (CompanyInfo companyInfo : companyInfos) {
					CustomerFollowUp cfu = new CustomerFollowUp();
					Integer id = companyInfo.getId();
					String userId = String.valueOf(companyInfo.getUserId());
					Integer companyId = companyInfo.getId();
					String userName = companyInfo.getUsername();
					String companyName = companyInfo.getCompanyName();
					cfu.setCompanyId(companyId);
					cfu.setCompanyName(companyName);
					cfu.setUserId(userId);
					cfu.setUserName(userName);
					cfu.setId(id);
					List<com.ys.web.entity.CustomerFollowUp> getcustomerFollowUpList = followUpService
							.getcustomerFollowUp(companyId, null, null);
					// 获取远程的最新跟进记录
					com.ys.web.entity.CustomerFollowUp remoteFollowContent = osCompanyInfoService
							.getOsNewFollowContent(companyId);
					if (getcustomerFollowUpList != null && !getcustomerFollowUpList.isEmpty()
							&& remoteFollowContent != null) {
						if (getcustomerFollowUpList.get(0).getFollowUpTime().getTime() > remoteFollowContent
								.getFollowUpTime().getTime()) {
							String followUpContent = getcustomerFollowUpList.get(0).getFollowUpContent();
							cfu.setFollowUpContent("<a href='javascript:' title=" + followUpContent.replaceAll(" ", "")
									+ " style='color:black;text-decoration:none;'>" + followUpContent + "</a>");
							String followUpTitle = getcustomerFollowUpList.get(0).getFollowUpTitle();
							cfu.setFollowUpTitle("<a href='javascript:' title=" + followUpTitle.replaceAll(" ", "")
									+ " style='color:black;text-decoration:none;'>" + followUpTitle + "</a>");
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date followUpTime = getcustomerFollowUpList.get(0).getFollowUpTime();
							String date = format.format(followUpTime);
							cfu.setFollowUpTime("<span style='color:black'>" + date + "</span>");
						} else {
							String followUpContent = remoteFollowContent.getFollowUpContent();
							cfu.setFollowUpContent("<a href='javascript:' title=" + followUpContent.replaceAll(" ", "")
									+ " style='color:#838B8B;text-decoration:none;'>" + followUpContent + "</a>");
							String followUpTitle = remoteFollowContent.getFollowUpTitle();
							cfu.setFollowUpTitle("<a href='javascript:' title=" + followUpTitle.replaceAll(" ", "")
									+ " style='color:#838B8B;text-decoration:none;'>" + followUpTitle + "</a>");
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date followUpTime = remoteFollowContent.getFollowUpTime();
							String date = format.format(followUpTime);
							cfu.setFollowUpTime("<span style='color:#838B8B'>" + date + "</span>");
						}
					}
					if (getcustomerFollowUpList != null && !getcustomerFollowUpList.isEmpty()
							&& remoteFollowContent == null) {
						String followUpContent = getcustomerFollowUpList.get(0).getFollowUpContent();
						cfu.setFollowUpContent("<a href='javascript:' title=" + followUpContent.replaceAll(" ", "")
								+ " style='color:black;text-decoration:none;'>" + followUpContent + "</a>");
						String followUpTitle = getcustomerFollowUpList.get(0).getFollowUpTitle();
						cfu.setFollowUpTitle("<a href='javascript:' title=" + followUpTitle.replaceAll(" ", "")
								+ " style='color:black;text-decoration:none;'>" + followUpTitle + "</a>");
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Date followUpTime = getcustomerFollowUpList.get(0).getFollowUpTime();
						String date = format.format(followUpTime);
						cfu.setFollowUpTime("<span style='color:black'>" + date + "</span>");
					}
					if (getcustomerFollowUpList.isEmpty() && remoteFollowContent != null) {
						String followUpContent = remoteFollowContent.getFollowUpContent();
						cfu.setFollowUpContent("<a href='javascript:' title=" + followUpContent.replaceAll(" ", "")
								+ " style='color:#838B8B;text-decoration:none;'>" + followUpContent + "</a>");
						String followUpTitle = remoteFollowContent.getFollowUpTitle();
						cfu.setFollowUpTitle("<a href='javascript:' title=" + followUpTitle.replaceAll(" ", "")
								+ " style='color:#838B8B;text-decoration:none;'>" + followUpTitle + "</a>");
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Date followUpTime = remoteFollowContent.getFollowUpTime();
						String date = format.format(followUpTime);
						cfu.setFollowUpTime("<span style='color:#838B8B'>" + date + "</span>");
					}
					customerFollowUp.add(cfu);
				}
				return customerFollowUp;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@RequestMapping(params = "getFollowUpList")
	@ResponseBody
	public List<CustomerFollowUp> getFollowUpList(HttpServletRequest httpServletRequest) {
		Integer companyId = Integer.valueOf(httpServletRequest.getParameter("id"));
		List<com.ys.web.entity.CustomerFollowUp> customerFollowUp = followUpService.getcustomerFollowUp(companyId, null,
				null);
		List<com.ys.web.entity.CustomerFollowUp> remoteOsCompanyInfo = osCompanyInfoService
				.getOsCompanyInfoByComId(companyId);
		List<CustomerFollowUp> list = new ArrayList<CustomerFollowUp>();
		CustomerFollowUp cfu = null;
		// 遍历kad系统的跟进记录
		if (customerFollowUp != null && !customerFollowUp.isEmpty()) {
			for (com.ys.web.entity.CustomerFollowUp l : customerFollowUp) {
				cfu = new CustomerFollowUp();
				cfu = new CustomerFollowUp();
				cfu.setId(l.getId());
				cfu.setUserId(l.getUserId());
				cfu.setUserName(l.getUserName());
				cfu.setCompanyId(l.getCompanyId());
				cfu.setCompanyName(l.getCompanyName());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String date = format.format(l.getFollowUpTime());
				cfu.setFollowUpTime(date);
				//内容过长时进行截取，后面部分用省略号显示，并且鼠标悬浮显示全部
				String followUpContent = l.getFollowUpContent();
				cfu.setFollowUpContent ("<a href='javascript:' title=" + followUpContent.replaceAll(" ", "")
				+ " style='color:black;text-decoration:none;'>" + followUpContent + "</a>");
				//标题过长时进行截取，后面部分用省略号显示，并且鼠标悬浮显示全部
				String followUpTitle = l.getFollowUpTitle();
				cfu.setFollowUpTitle("<a href='javascript:' title=" + followUpTitle.replaceAll(" ", "")
				+ " style='color:black;text-decoration:none;'>" + followUpTitle + "</a>");
				list.add(cfu);
			}
		}
		// 遍历远程sms系统的跟进记录
		if (remoteOsCompanyInfo != null && !remoteOsCompanyInfo.isEmpty()) {
			for (com.ys.web.entity.CustomerFollowUp ll: remoteOsCompanyInfo) {
				cfu = new CustomerFollowUp();
				cfu.setId(ll.getId());
				cfu.setUserId(ll.getUserId());
				cfu.setUserName(ll.getUserName());
				cfu.setCompanyId(ll.getCompanyId());
				cfu.setCompanyName(ll.getCompanyName());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String date = format.format(ll.getFollowUpTime());
				cfu.setFollowUpTime(date);
				//内容过长时进行截取，后面部分用省略号显示，并且鼠标悬浮显示全部
				String followUpContent = ll.getFollowUpContent();
				cfu.setFollowUpContent("<a href='javascript:' title=" + followUpContent.replaceAll(" ", "")
				+ " style='color:#838B8B;text-decoration:none;'>" + followUpContent + "</a>");
				//标题过长时进行截取，后面部分用省略号显示，并且鼠标悬浮显示全部
				String followUpTitle = ll.getFollowUpTitle();
				cfu.setFollowUpTitle("<a href='javascript:' title=" + followUpTitle.replaceAll(" ", "")
				+ " style='color:#838B8B;text-decoration:none;'>" + followUpTitle + "</a>");
				list.add(cfu);
			}
		}
		Collections.sort(list);
		List<CustomerFollowUp> backList = new ArrayList<CustomerFollowUp>();
		for (CustomerFollowUp ls : list) {
			cfu = new CustomerFollowUp();
			cfu.setId(ls.getId());
			cfu.setCompanyId(ls.getCompanyId());
			cfu.setCompanyName(ls.getCompanyName());
			cfu.setFollowUpContent(ls.getFollowUpContent());
			cfu.setFollowUpTitle(ls.getFollowUpTitle());
			cfu.setUserId(ls.getUserId());
			if(ls.getFollowUpTitle().contains("color:#838B8B")){
				cfu.setUserName("<span style='color:#838B8B'>" + ls.getUserName() + "</span>");
				cfu.setFollowUpTime("<span style='color:#838B8B'>" + ls.getFollowUpTime() + "</span>");
			}else {
				cfu.setUserName("<span style='color:black'>" + ls.getUserName() + "</span>");
				cfu.setFollowUpTime("<span style='color:black'>" + ls.getFollowUpTime() + "</span>");
			}
			backList.add(cfu);
		}
		return backList;
	}

	@RequestMapping(params = "addFollowUp")
	@ResponseBody
	public AjaxJson addFollowUp(HttpSession session, HttpServletRequest httpServletRequest) {
		String followUpTitle = httpServletRequest.getParameter("followUpTitle");
		String followUpContent = httpServletRequest.getParameter("followUpContent");
		int companyId = Integer.valueOf((httpServletRequest.getParameter("companyId")));
		Integer operateUserId = (Integer) session.getAttribute("userId");
		AjaxJson ajaxJson = new AjaxJson();
		if (followUpContent.trim() == null || followUpContent.trim().length() == 0
				|| followUpContent.trim().equals("")) {
			ajaxJson.setMsg("跟进内容为空，请编辑后添加！");
			ajaxJson.setSuccess(false);
			return ajaxJson;
		} else {
			List<User> user = followUpService.getEmployeeName(operateUserId);
			String userName = "";
			int addFollowUp = 0;
			if (user != null && !user.isEmpty()) {
				userName = user.get(0).getEmployeeName();
			}
			addFollowUp = followUpService.addFollowUp(followUpTitle, followUpContent, userName, operateUserId,
					companyId);
			if (addFollowUp == 1) {
				ajaxJson.setMsg("添加成功！");
				ajaxJson.setSuccess(true);
				return ajaxJson;
			} else {
				ajaxJson.setMsg("添加失败！");
				ajaxJson.setSuccess(false);
				return ajaxJson;
			}
		}
	}

	@RequestMapping(params = "getFollowUpDetail")
	@ResponseBody
	public AjaxJson getFollowUpDetail(HttpSession session, HttpServletRequest httpServletRequest) {
		int followUpId = Integer.valueOf(httpServletRequest.getParameter("follow_up_id"));
		String followUpContent = httpServletRequest.getParameter("followUpContent");
		List<com.ys.web.entity.CustomerFollowUp> followUpDetailList =null;
		if(followUpContent.contains("color:#838B8B")){
			 com.ys.web.entity.CustomerFollowUp followUpDetai = osCompanyInfoService.getDetalisCompanyInfoById(followUpId);
			 AjaxJson ajaxJson = new AjaxJson();
			 if(followUpDetai!=null){
				 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Map<String, Object> backDataMap = new HashMap<String, Object>();
					backDataMap.put("followUpTitle", followUpDetai.getFollowUpTitle());
					backDataMap.put("followUpContent", followUpDetai.getFollowUpContent());
					backDataMap.put("userName", followUpDetai.getUserName());
					String date = format.format(followUpDetai.getFollowUpTime());
					backDataMap.put("followUpTime", date);
					ajaxJson.setSuccess(true);
					ajaxJson.setAttributes(backDataMap);
					return ajaxJson;
			 }else{
				 ajaxJson.setSuccess(false);
					ajaxJson.setMsg("数据错误！");
					return ajaxJson;
			 }
		}else{
			followUpDetailList = followUpService.getFollowUpDetail(followUpId);
			AjaxJson ajaxJson = new AjaxJson();
			if (followUpDetailList != null && !followUpDetailList.isEmpty()) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Map<String, Object> backDataMap = new HashMap<String, Object>();
				com.ys.web.entity.CustomerFollowUp followUpDetai = followUpDetailList.get(0);
				backDataMap.put("followUpTitle", followUpDetai.getFollowUpTitle());
				backDataMap.put("followUpContent", followUpDetai.getFollowUpContent());
				backDataMap.put("userName", followUpDetai.getUserName());
				String date = format.format(followUpDetai.getFollowUpTime());
				backDataMap.put("followUpTime", date);
				ajaxJson.setSuccess(true);
				ajaxJson.setAttributes(backDataMap);
				return ajaxJson;
			} else {
				ajaxJson.setSuccess(false);
				ajaxJson.setMsg("数据错误！");
				return ajaxJson;
			}
		}
	}

}
